package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    @Autowired
    private IUserService userService;

    @Override
    public Result queryById(Long id) {

        Blog blog = getById(id);

        if(blog==null)
            return Result.fail("笔记不存在");


        this.isBlogLiked(blog);
        return Result.ok(blog);

    }

    @Override
    public Result queryHotBlog(Integer current) {
        return null;
    }

    public Result likeBlog(Long blogId){
        Long userId= UserHolder.getUser().getId();
        String key = "blog:liked:"+blogId;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        if(score==null){
            boolean success = update().setSql("liked=liked+1").eq("id", blogId).update();
            if(success)
                stringRedisTemplate.opsForZSet().add(key, userId.toString(),System.currentTimeMillis());
        }else {
            boolean success=update().setSql("liked=liked-1").eq("id",blogId).update();
            if(success)
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
        }



        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key= RedisConstants.BLOG_LIKED_KEY+id;
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(range==null||range.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 2.解析出其中的用户id
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        // 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4.返回
        return Result.ok(userDTOS);

    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean success  = save(blog);
        if(!success){
            return Result.fail("发布失败");
        }

        //查询作者所有粉丝
        List<Follow> follows = followService.query().eq("follower_user_id", user.getId()).list();

        for (Follow follow : follows) {
            Long userId = follow.getUserId();
            String key = FEED_KEY+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());

        }
        return Result.ok(blog.getId());

    }

    @Override
    public Result getBlogOfFollow(Long max, Integer offset) {

        Long userId = UserHolder.getUser().getId();
        String key = FEED_KEY+userId;

        Set<ZSetOperations.TypedTuple<String>> typedTuples =
                stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if(typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime=0;
        int os=1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            long time = typedTuple.getScore().longValue();
            if(minTime!=time){
                minTime=time;
                os=1;
            }else {
                os++;
            }
        }
        os=minTime==max?os:os+offset;
        String idStr = StrUtil.join(",", ids);

        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id" + idStr + ")").list();
        for (Blog blog : blogs) {

            isBlogLiked(blog);

        }

        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setOffset(os);
        result.setMinTime(minTime);


        return Result.ok(result);
    }



    private void isBlogLiked(Blog blog){

        UserDTO user = UserHolder.getUser();
        if(user==null){
            return;
        }

        Long userId= user.getId();
        String key = "blog:liked:"+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        blog.setIsLike(score!=null);
    }

}
